import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_kit/wechat_kit.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/pay/ali_pay_utils.dart';
import 'package:tracker/common/pay/model/order_info_req.dart';
import 'package:tracker/common/pay/wxpay_utils.dart';
import 'package:tracker/common/widget/pay_dialog_widget.dart';
import 'package:tracker/pages/home/flowcard/model/card_packages_resp.dart';
import 'package:tracker/pages/home/vip/enum/buy_type.dart';
import 'package:tracker/pages/home/vip/model/vip_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

class VipPage extends ConsumerStatefulWidget {
  const VipPage({super.key});

  @override
  ConsumerState<VipPage> createState() => _VipPageState();
}

class _VipPageState extends ConsumerState<VipPage> {
  bool showLoading = false;

  /// 所有套餐
  VipInfoData vipInfoData = VipInfoData();

  /// 允许展示的套餐
  List<VipPackage> vipPackageList = [];

  /// 当选选中的购买类型
  BuyType selectedBuyType = BuyType.deviceRenewal;

  /// 选中的套餐下标
  int selectedPackageIndex = 0;

  /// 套餐配置，允许展示的套餐
  final List<BuyType> _buyTypeList = [
    BuyType.deviceRenewal,
  ];

  PayDialogWidget payDialogWidget = PayDialogWidget();

  final alipayUtils = AliPayUtils();
  final wxpayUtils = WxpayUtils();

  Future<void> _fetchDeviceInfo() async {
    await ref.read(deviceInfoProvider.notifier).refresh(() {});
    setState(() {
      showLoading = false;
    });
  }

  _fetchVipInfo() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    ToastUtils.showLoading();
    final res = await get<VipInfoResp, VipInfoResp>('', decodeType: VipInfoResp());
    res.when(
        success: (resp) {
          ToastUtils.dismissLoading();
          if (resp.code == 200) {
            setState(() {
              vipInfoData = resp.data!;
              // 只展示_packageConfigList中配置的套餐
              vipPackageList = resp.data!.packages!.where((element) {
                return _buyTypeList.any((buyType) => buyType.value == element.packageType);
              }).toList();
            });
          } else {
            ToastUtils.showToast(resp.msg ?? '获取套餐信息失败');
          }
        },
        failure: (String msg, int code) {});
  }

  _showLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  Widget _buildBodyView() {
    return Stack(fit: StackFit.expand, children: [
      SingleChildScrollView(
          child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
        // 顶部背景
        Container(
          width: ScreenUtil.getScreenW(context),
          // height: 200,
          decoration: BoxDecoration(color: ColorUtils.hexToColor('#292b35')),
          child: Column(
            children: [
              // 设备信息
              _buildDeviceInfoView(),
              // 购买类型标签
              _buildBuyTypeTabView(),
            ],
          ),
        ),
        Container(
            padding: const EdgeInsets.only(top: 8),
            child: Text(
              '请选择套餐',
              style: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 17, fontWeight: FontWeight.bold),
            )),
        const SizedBox(height: 20),
        // 套餐列表
        _buildVipPackageListView(),
        // 套餐内容
        _buildPackageContentView(),
      ])),
      // 底部按钮
      _buildBottomBtn(),
    ]);
  }

  _buildDeviceInfoView() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    return Container(
      width: ScreenUtil.getScreenW(context),
      // height: 200,
      padding: const EdgeInsets.only(
        left: 20,
        right: 20,
        top: 20,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 设备名称
          Text(
            '设备名称: ${deviceInfo.deviceName}',
            style: TextStyle(
              color: ColorUtils.hexToColor('#f0c989'),
              fontSize: 16,
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '设备号: ${deviceInfo.imei}',
                style: TextStyle(
                  color: ColorUtils.hexToColor('#f0c989'),
                  fontSize: 16,
                ),
              ),
              const SizedBox(width: 20),
              // 申请退款
              GestureDetector(
                onTap: () {
                  ToastUtils.showSimpleBottomDialog(
                    context,
                    title: '申请退款',
                    content: '尊敬的用户，如您已购买套餐，购买成功之后可以申请退款，客服人员将及时为您处理。',
                    confirmTitle: '好的',
                  );
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  alignment: AlignmentDirectional.bottomEnd,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: ColorUtils.hexToColor('#f0c989'),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    '申请退款',
                    style: TextStyle(
                      color: ColorUtils.hexToColor('#f0c989'),
                      fontSize: 12,
                      // decoration: TextDecoration.underline,
                      // decorationStyle: TextDecorationStyle.solid,
                      // decorationThickness: 1,
                      // decorationColor: ColorUtils.hexToColor('#f0c989'),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Text(
            _buildExpireText(),
            style: TextStyle(
              color: ColorUtils.hexToColor('#f0c989'),
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }

  String _buildExpireText() {
    var text = '';
    // 设备续期
    if (vipInfoData.deviceRenewal != null) {
      // 判断是否到期
      if (vipInfoData.deviceRenewal?.expired == true) {
        text = '设备未激活或已到期，请购买套餐';
      } else {
        text = '到期时间：${vipInfoData.deviceRenewal?.expireTime ?? ''}';
      }
    }
    return text;
  }

  Widget _buildBuyTypeTabView() {
    final itemWidth = (ScreenUtil.getScreenW(context) - 60) / 2;
    const itemHeight = 40.0;
    return Padding(
      padding: const EdgeInsets.all(20),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: vipPackageList.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          childAspectRatio: itemWidth / itemHeight,
          crossAxisCount: 2,
          crossAxisSpacing: 20,
          mainAxisSpacing: 20,
        ),
        itemBuilder: (context, index) {
          final vipPackage = vipPackageList[index];
          final isSelected = selectedBuyType.value == vipPackage.packageType;
          return Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: isSelected ? ColorUtils.hexToColor('#fff3dd') : ColorUtils.hexToColor('#292b35'),
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: ColorUtils.hexToColor('#f0c989'),
                width: 1,
              ),
            ),
            child: Text(
              vipPackage.packageTypeName ?? '',
              style: isSelected
                  ? TextStyle(color: ColorUtils.hexToColor('#dc8b1c'), fontSize: 16)
                  : TextStyle(color: ColorUtils.hexToColor('#f0c989'), fontSize: 16),
            ),
          );
        },
      ),
    );
  }

  /// 套餐列表
  Widget _buildVipPackageListView() {
    if (vipPackageList.isEmpty) {
      return Container();
    }
    final vipPackage = vipPackageList.firstWhere((element) => element.packageType == selectedBuyType.value);
    final List<VipPackageInfo> packageInfos = vipPackage.packageInfos ?? [];
    // 水平方向显示2.5个
    final itemWidth = (ScreenUtil.getScreenW(context) - 60) / 2.5;
    // 横向滚动的宫格列表
    return Container(
      width: double.infinity,
      height: 120,
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: GridView.builder(
        padding: const EdgeInsets.only(
          left: 20,
          right: 20,
        ),
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        physics: const ScrollPhysics(),
        itemCount: packageInfos.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          childAspectRatio: 120 / itemWidth,
          crossAxisCount: 1,
          crossAxisSpacing: 20,
          mainAxisSpacing: 20,
          // mainAxisExtent: 120
        ),
        itemBuilder: (context, index) {
          final packageInfo = packageInfos[index];
          final isSelected = selectedPackageIndex == index;
          return GestureDetector(
            onTap: () {
              setState(() {
                selectedPackageIndex = index;
              });
            },
            child: Container(
              decoration: BoxDecoration(
                color: isSelected ? ColorUtils.hexToColor('#fff3dd') : Colors.transparent,
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: isSelected ? ColorUtils.hexToColor('#ffb15f') : ColorUtils.hexToColor('#cccccc'),
                  width: 1,
                ),
              ),
              padding: const EdgeInsets.only(
                left: 8,
                right: 8,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  // 套餐名称
                  Text(
                    '${packageInfo.name ?? ''}',
                    style: TextStyle(
                      color: AppTheme.themeConfig.primaryTextColor,
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  Column(
                    children: [
                      // 套餐价格
                      Text(
                        '￥${packageInfo.price ?? ''}',
                        style: TextStyle(
                          color: isSelected ? ColorUtils.hexToColor('#a95c15') : AppTheme.themeConfig.primaryTextColor,
                          fontSize: 20,
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                      // 原价
                      Text(
                        '￥${packageInfo.originalPrice ?? ''}',
                        style: TextStyle(
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontSize: 13,
                          // 删除线
                          decoration: TextDecoration.lineThrough,
                          decorationColor: AppTheme.themeConfig.primaryTextColor,
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /// 套餐内容
  Widget _buildPackageContentView() {
    if (vipPackageList.isEmpty) {
      return Container();
    }
    final vipPackage = vipPackageList.firstWhere((element) => element.packageType == selectedBuyType.value);
    final List<VipPackageInfo> packageInfos = vipPackage.packageInfos ?? [];
    if (packageInfos.isEmpty) {
      return Container();
    }
    final packageInfo = packageInfos[selectedPackageIndex];
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.only(left: 20, right: 20, bottom: 90),
      padding: const EdgeInsets.symmetric(
        horizontal: 12,
        vertical: 8,
      ),
      // 矩形边框
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: ColorUtils.hexToColor('#cccccc'),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '套餐内容：',
            style: TextStyle(
              color: AppTheme.themeConfig.primaryTextColor,
              fontSize: 17,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            '${packageInfo.description ?? ''}',
            style: TextStyle(
              color: AppTheme.themeConfig.primaryTextColor,
              fontSize: 15,
            ),
          ),





      ],
      ),
    );
  }

  Widget _buildBottomBtn() {
    if (vipPackageList.isEmpty) {
      return Container();
    }
    final vipPackage = vipPackageList.firstWhere((element) => element.packageType == selectedBuyType.value);
    final List<VipPackageInfo> packageInfos = vipPackage.packageInfos ?? [];
    if (packageInfos.isEmpty) {
      return Container();
    }
    final packageInfo = packageInfos[selectedPackageIndex];
    // 已省多少钱
    final savePrice = NumUtils.formatNum(packageInfo.originalPrice! - packageInfo.price!);
    return Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: Container(
        height: 50,
        decoration: BoxDecoration(
          color: ColorUtils.hexToColor('#292b35'),
          borderRadius: const BorderRadius.all(
            Radius.circular(25),
          ),
        ),
        child: TextButton(
          onPressed: () {
            _showPayDialog();
          },
          child: Text(
            '￥${packageInfo.price ?? ''}立即购买(已省${savePrice})元',
            style: TextStyle(
              color: ColorUtils.hexToColor('#f5cf8f'),
              fontSize: 17,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }

  /// 购买弹窗
  _showPayDialog() {
    if (vipPackageList.isEmpty) {
      ToastUtils.showToast('未查询到套餐信息');
      return;
    }
    final vipPackage = vipPackageList.firstWhere((element) => element.packageType == selectedBuyType.value);
    if (vipPackage.packageInfos == null || vipPackage.packageInfos!.isEmpty) {
      ToastUtils.showToast('未查询到套餐信息');
      return;
    }
    final List<VipPackageInfo> packageInfos = vipPackage.packageInfos ?? [];
    if (packageInfos.isEmpty) {
      ToastUtils.showToast('未查询到套餐信息');
      return;
    }
    final packageInfo = packageInfos[selectedPackageIndex];
    payDialogWidget.showPayDialog(context, '${packageInfo.price}', onConfirm: (payType) {
      _handleBuy(payType);
    });
  }

  /// 购买
  _handleBuy(PayType payType) {
    final deviceInfo = ref.watch(deviceInfoProvider);

    if (vipPackageList.isEmpty) {
      ToastUtils.showToast('未查询到套餐信息');
      return;
    }
    final vipPackage = vipPackageList.firstWhere((element) => element.packageType == selectedBuyType.value);
    if (vipPackage.packageInfos == null || vipPackage.packageInfos!.isEmpty) {
      ToastUtils.showToast('未查询到套餐信息');
      return;
    }
    final List<VipPackageInfo> packageInfos = vipPackage.packageInfos ?? [];
    if (packageInfos.isEmpty) {
      ToastUtils.showToast('未查询到套餐信息');
      return;
    }
    // 支付方式
    final payAccount = PayUtils.getPayAccount(payType);
    final payTypeParams = PayUtils.getPayType(payType);
    final packageInfo = packageInfos[selectedPackageIndex];
    final orderInfoReq = OrderInfoReq(
      imei: vipInfoData.imei,
      payType: payTypeParams,
      payAccount: payAccount,
      orderType: 2,
      flowPackage: PackageInfo(
        packageCode: packageInfo.id.toString(),
        price: packageInfo.price,
        packageName: packageInfo.name,
        timeLength: packageInfo.durationNum,
        timeUnit: packageInfo.durationUnit.toString(),
        packageId: packageInfo.id,
        packageType: selectedBuyType.value,
      ),
    );
    XLogger.debug('orderInfoReq: ${orderInfoReq.toJson()}');
    if (payType == PayType.alipay) {
      alipayUtils.createOrder(orderInfoReq);
    } else if (payType == PayType.wechat) {
      // wxpayUtils.createOrder(orderInfoReq);
      wxpayUtils.createOrder(deviceInfo.imei ?? "", packageInfo.id ?? 0);
    } else if (payType == PayType.wechatUnion) {
      wxpayUtils.createMiniAppOrder(orderInfoReq);
    }
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      showLoading = true;
    });
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _fetchDeviceInfo();
      await _fetchVipInfo();
      wxpayUtils.registerWechatResp((resp) {
        if (resp is WechatLaunchMiniProgramResp) {
          XLogger.info('拉起小程序: ${resp.errorCode} ${resp.errorMsg}, isSuccessful: ${resp.isSuccessful}');
          XLogger.info('拉起小程序 exMsg: ${resp.extMsg}');
          if (resp.isSuccessful) {
            // 支付成功
            ToastUtils.showSimpleDialog(context,
                title: '提示', content: '套餐购买成功', confirmTitle: '好的', confirmCallback: () {});
            // 刷新套餐信息
            _fetchDeviceInfo();
            _fetchVipInfo();
          } else {
            // 支付失败
            ToastUtils.showToast('支付失败');
          }
        }
      });
    });
    alipayUtils.listenPay((resp) {
      XLogger.info('VIP支付结果：${resp.resultStatus}');
      if (resp.isSuccessful) {
        // 支付成功
        ToastUtils.showSimpleDialog(context,
            title: '提示', content: '套餐购买成功', confirmTitle: '好的', confirmCallback: () {});
        // 刷新套餐信息
        _fetchDeviceInfo();
        _fetchVipInfo();
      } else {
        // 支付失败
        ToastUtils.showToast('支付失败');
      }
    });
    // wxpayUtils.registerWechatResp((resp) {
    //   XLogger.info('支付结果：${resp.errorCode}, ${resp.errorMsg}');
    //   if (resp.isSuccessful) {
    //     // 支付成功
    //     // 支付成功
    //     ToastUtils.showSimpleDialog(
    //         context,
    //         title: '提示',
    //         content: '套餐购买成功',
    //         confirmTitle: '好的',
    //         confirmCallback: () {
    //         }
    //     );
    //     // 刷新套餐信息
    //     _fetchDeviceInfo();
    //     _fetchVipInfo();
    //   } else {
    //     // 支付失败
    //     ToastUtils.showToast('支付失败');
    //   }
    // });
  }

  @override
  void dispose() {
    super.dispose();
    alipayUtils.dispose();
    wxpayUtils.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '购买套餐',
        ),
        centerTitle: true,
        backgroundColor: ColorUtils.hexToColor('#292b35'),
        foregroundColor: ColorUtils.hexToColor('#f0c989'),
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: showLoading ? _showLoading() : _buildBodyView(),
    );
  }
}

class VipPackageConfig {
  int packageType;
  String packageName;
  String packageProperty;
  VipPackageConfig({
    required this.packageType,
    required this.packageName,
    required this.packageProperty,
  });
}
